<?php

namespace app\user\controller;
use app\common\controller\UserBase;
use app\common\model\Customer as Kehu;
use app\common\model\CustomerTrack;
use app\common\model\CustomerRemind;
use app\common\model\UserConfig;
use app\common\model\CustomerOrder;

class Customer extends UserBase
{
    protected function _initialize()
    {
        parent::_initialize();
        !config('website_status') && die(config('colse_explain'));
        $config = cache('db_config_data');
        if (!$config) {
            $config = [];
            foreach (model('config')->select() as $v) {
                $config[$v['group']][$v['name']] = $v['value'];
            }
            cache('db_config_data', $config);
        }
        config($config);
    }
    //客户列表
    public function index()
    {
        default_config('customer');//默认客户参数
        $customer = new Kehu();
        if (input('cname')) {
            $customer ->where('cname like "%' . input('cname') .'%"');
        }
        //筛选
        if(input('type')){
            $customer ->where('type='.input('type'));
        }
        //筛选
        if(input('intention')){
            $customer ->where('intention='.input('intention'));
        }
        //筛选
        if(input('come_from')){
            $customer ->where('come_from='.input('come_from'));
        }
        //筛选
        if(input('status')){
            $customer ->where('status='.input('status'));
        }
        //筛选
        if(input('screen')){
            switch (input('screen')){
                case "star":
                    $customer ->where('intention>=3')->order('intention desc')->order('update_time desc');
                    break;
                case "today_add":
                    //今日
                    $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    $customer ->where('create_time >='.$beginToday.' and create_time <='.$endToday)->order('update_time desc');
                    break;
                case "today_track":
                    //今日
                    $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    $customer ->where('update_time >='.$beginToday.' and update_time <='.$endToday)->order('update_time desc');
                    break;
                case "30day_notrack":
                    //今日
                    $day = date("Y-m-d",strtotime("-30 day"));
                    $customer ->where('update_time <='.$day)->order('update_time desc');
                    break;
                case "notrack":
                    $customer ->where('update_time = 0')->order('update_time desc');
                    break;
                default:
            }
        }
        //筛选
        $type = UserConfig::where(['name'=>'type','shop_id'=>session('user_auth.shop_id')])->find();
        $status = UserConfig::where(['name'=>'status','shop_id'=>session('user_auth.shop_id')])->find();
        $come_from = UserConfig::where(['name'=>'come_from','shop_id'=>session('user_auth.shop_id')])->find();
        $intention = UserConfig::where(['name'=>'intention','shop_id'=>session('user_auth.shop_id')])->find();
        $list = $customer->where('is_public = 1')->order('id desc')->paginate(config('page_number'));
        return $this->fetch(is_Client('index'),[
            'list' => $list,
            'type' => $type,
            'status' => $status,
            'come_from' => $come_from,
            'intention' => $intention,
        ]);
    }
    //客户列表
    public function publiccus()
    {
        default_config('customer');//默认客户参数
        $customer = new Kehu();
        if (input('cname')) {
            $customer ->where('cname like "%' . input('cname') .'%"');
        }
        //筛选
        if(input('type')){
            $customer ->where('type='.input('type'));
        }
        //筛选
        if(input('intention')){
            $customer ->where('intention='.input('intention'));
        }
        //筛选
        if(input('come_from')){
            $customer ->where('come_from='.input('come_from'));
        }
        //筛选
        if(input('status')){
            $customer ->where('status='.input('status'));
        }
        //筛选
        $type = UserConfig::where(['name'=>'type','shop_id'=>session('user_auth.shop_id')])->find();
        $status = UserConfig::where(['name'=>'status','shop_id'=>session('user_auth.shop_id')])->find();
        $come_from = UserConfig::where(['name'=>'come_from','shop_id'=>session('user_auth.shop_id')])->find();
        $intention = UserConfig::where(['name'=>'intention','shop_id'=>session('user_auth.shop_id')])->find();
        
        $list = $customer->where('is_public = 0')->order('id desc')->paginate(config('page_number'));
        return $this->fetch(is_Client('publiccus'),[
            'list' => $list,
            'type' => $type,
            'status' => $status,
            'come_from' => $come_from,
            'intention' => $intention,
        ]);
    }
    //占用客户
    public function get_cus()
    {
        $id = input('id');
        //检查该客户是否被占用
        $customer = model('customer')->get($id);
        if($customer['is_public']=='1'){
            $this->error('客户已被占用');
        }
        //开始占用
        model('customer')->where(['id'=>$id])->update(['is_public'=>'1','uid'=>session('user_auth.user_id')]);
        $this->success('占用成功', url('user/customer/show',['id' =>$id]));
        
    }
    //查看客户
    public function show()
    {
        $id = input('id');
        //客户信息
        $customer = Kehu::get($id);
        //跟踪信息
        $track = CustomerTrack::where(['cid'=>$customer['id']])->order('id desc')->paginate(6);
        //提醒信息
        $remind = CustomerRemind::where(['cid'=>$customer['id']])->order('id desc')->limit(15)->select();
        //订单信息
        $order = CustomerOrder::where(['cid'=>$customer['id']])->order('id desc')->limit(15)->select();
        //自定义字段
        $config_customer = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,'is_sys' => '0'])->order('sort_order asc')->select();
        //自定义字段
        $config_track = model('user_config')->where([ 'group'  => 'track', 'status' => 1,'is_sys' => '0'])->order('sort_order asc')->select();
        return $this->fetch(is_Client('show'),[
            'id' => $id,
            'customer' => $customer,
            'track' => $track,
            'remind' => $remind,
            'order' => $order,
            'config_customer' => $config_customer,
            'config_track' => $config_track,
        ]);
    }
    //添加
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['shop_id'] = session('user_auth.shop_id');
            $param['create_time'] = time();
            $param['update_time'] = time();
            $param['jdata'] = $param;
            if(input('type')!='public'){
                $param['uid'] = session('user_auth.user_id');
                $param['is_public'] = 1;
            }
            $data = $this->insert('customer', $param);
            
            if ($data === true) {
                insert_user_log('添加了客户："'.$param['cname'].'"');
                if(input('type')!='public'){
                    $this->success('添加成功', url('user/customer/show',['id' => $this->insertId]));
                }else{
                    $this->success('添加成功', url('user/customer/publiccus'));
                }
            }else{
                $this->error($this->errorMsg);
            }
        }
        default_config('customer');//默认客户参数
        //读取字段
        $config = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,])->order('sort_order asc')->select();
        
        $data['province'] = '福建';
        $data['city'] = '福州';
        $data['area'] = '鼓楼区';
        return $this->fetch(is_Client('add'),[
            'data' => $data,
            'config' => $config,
        ]);
    }
    //客户修改
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['update_time'] = time();
            $param['jdata'] = $param;
            if (is_array($param['id'])) {
                $data = [];
                foreach ($param['id'] as $v) {
                    $data[] = ['id' => $v, $param['name'] => $param['value']];
                }
                $result = $this->saveAll('customer', $data, input('_verify', true));
            } else {
                $result = $this->update('customer', $param, input('_verify', true));
            }
            if ($result === true) {
                insert_user_log('修改了客户："'.$param['cname'].'"');
                $this->success('修改成功', url('user/customer/show',['id' => $param['id']]));
            } else {
                $this->error($this->errorMsg);
            }
        }
        //读取字段
        $config = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,])->order('sort_order asc')->select();
        return $this->fetch(is_Client('edit'), ['data' => model('customer')->get(input('id')),'config' => $config,]);
    }
    //客户删除
    public function del()
    {
        if ($this->request->isPost()) {
            if ($this->delete_recovery('customer', $this->request->param()) === true) {
                //同时删除跟进记录
                model('customerTrack')->where(['cid'=>$this->request->param['cid']])->update(['delete_time'=>time()]);
                //同时删除提醒
                model('customerRemind')->where(['cid'=>$this->request->param['cid']])->update(['delete_time'=>time()]);
                //同时删除跟进记录
                model('customerOrder')->where(['cid'=>$this->request->param['cid']])->update(['delete_time'=>time()]);
                insert_user_log('删除了文章');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }
    //客户跟踪列表
    public function track()
    {
        $list = CustomerTrack::order('update_time desc,create_time desc,id desc')->paginate(config('page_number'));
        return $this->fetch(is_Client('track'),[
            'list' => $list,
            
        ]);
    }
    //添加跟踪记录
    public function add_track()
    {
        default_config('track');//默认跟踪参数
        $id = input('id');
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $param['cid'] = $id;
            $param['shop_id'] = session('user_auth.shop_id');
            $param['uid'] = session('user_auth.user_id');
            $param['create_time'] = time();
            $param['type'] = $params['type'];
            $param['remark'] = $params['remark'];
            $param['jdata'] = $params;
            $data = $this->insert('customer_track', $param);
            //更新客户信息
            if(isset($params['update_customer']) and $params['update_customer']=='on'){
                model('customer')->where(['id'=>$id])->update([
                    'update_time' => time(),
                    'type' => $params['customer']['type'],
                    'come_from' => $params['customer']['come_from'],
                    'intention' => $params['customer']['intention'],
                    'status' => $params['customer']['status'],
                ]);
            }else{
                Kehu::update_customers($id,['update_time' => time()]);
            }
            if ($data === true) {
                insert_user_log('添加了客户跟踪记录');
                $this->success('添加成功',url('user/customer/show',['id' => $id]));
            } else {
                $this->error($this->errorMsg);
            }
        }
        //读取字段
        $config = model('user_config')->where([ 'group'  => 'track', 'status' => 1])->order('sort_order asc')->select();
        $config_customer = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,'is_sys'=>1])->order('sort_order asc')->select();
        $customer = model('customer')->get($id);
        return $this->fetch(is_Client('add_track'),[
            'config' => $config,
            'config_customer' => $config_customer,
            'customer' => $customer,
        ]);
    }
    //客户跟踪记录修改
    public function edit_track()
    {
        $id = input('id');
        $data = model('customer_track')->get(input('id'));
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['update_time'] = time();
            $param['jdata'] = $param;
            if (is_array($param['id'])) {
                $data = [];
                foreach ($param['id'] as $v) {
                    $data[] = ['id' => $v, $param['name'] => $param['value']];
                }
                $result = $this->saveAll('customer_track', $data, input('_verify', true));
            } else {
                $result = $this->update('customer_track', $param, input('_verify', true));
            }
            //更新客户信息
            if(isset($param['update_customer']) and $param['update_customer']=='on'){
                model('customer')->where(['id'=>$data['cid']])->update([
                    'update_time' => time(),
                    'type' => $param['customer']['type'],
                    'come_from' => $param['customer']['come_from'],
                    'intention' => $param['customer']['intention'],
                    'status' => $param['customer']['status'],
                ]);
            }else{
                Kehu::update_customers($data['cid'],['update_time' => time()]);
            }
            if ($result === true) {
                insert_user_log('修改了客户跟踪记录');
                $this->success('修改成功', url('user/customer/show',['id' => $data['cid']]));
            } else {
                $this->error($this->errorMsg);
            }
        }
        //读取字段
        $config = model('user_config')->where([ 'group'  => 'track', 'status' => 1])->order('sort_order asc')->select();
        $config_customer = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,'is_sys'=>1])->order('sort_order asc')->select();
        $customer = model('customer')->get($data['cid']);
        return $this->fetch(is_Client('edit_track'), [
            'config' => $config,
            'config_customer' => $config_customer,
            'customer' => $customer,
            'data' => $data,
            ]
        );
    }
    //跟踪记录删除
    public function del_track()
    {
        if ($this->request->isPost()) {
            if ($this->delete_recovery('customer_track', $this->request->param()) === true) {
                insert_user_log('删除了跟踪记录');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }
    //提醒列表
    public function remind()
    {
        $type = input('type');
        //今日
        $beginToday = mktime(0,0,0,date('m'),date('d'),date('Y'));
    	$endToday = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        switch ($type){
            case "1"://今日待处理
                model('customerRemind')->where('remind_time >='.$beginToday.' and remind_time <='.$endToday.' and status=0');
                break;
            case "2"://全部待处理
                model('customerRemind')->where('status=0');
                break;
            case "3"://已处理提醒
                model('customerRemind')->where('status=1');
                break;
            case "4"://需二次处理
                model('customerRemind')->where('status=2');
                break;
            case "5"://已处理提醒
                model('customerRemind')->where('remind_time >='.$beginToday.' and status=0');
                break;
            default:
                model('customerRemind')->where('remind_time >='.$beginToday.' and remind_time <='.$endToday.' and status=0');
        }
        $list = model('customerRemind')->order('remind_time desc,status_time desc,id desc')->paginate(config('page_number'));
        return $this->fetch(is_Client('remind'),[
            'list' => $list,
        ]);
    }
    //添加提醒
    public function add_remind()
    {
        $id = input('id');
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $param['cid'] = $id;
            $param['shop_id'] = session('user_auth.shop_id');
            $param['uid'] = session('user_auth.user_id');
            $param['create_time'] = time();
            $param['remind_time'] = strtotime($params['remind_time']);
            $param['remark'] = $params['remark'];
            $param['jdata'] = $params['jdata'];
            $data = $this->insert('customer_remind', $param);
            //更新客户状态
            Kehu::update_customers($id,['update_time' => time()]);
            if ($data === true) {
                insert_user_log('添加了客户提醒记录');
                $this->success('添加成功',url('user/customer/show',['id' => $id]));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch(is_Client('add_remind'));
    }
    //设置提醒
    public function set_remind()
    {
        $id = input('id');
        $data = model('customerRemind')->get($id);
        if ($this->request->isPost()) {
            $param = $this->request->param();
            CustomerRemind::where(['id'=>$id])->update([
                'status' => $param['status'],
                'status_time' => time(),
                'status_time' => time(),
                'status_remark' => $param['status_remark'],
            ]);
            //更新客户信息
            if(isset($param['update_customer']) and $param['update_customer']=='on'){
                model('customer')->where(['id'=>$data['cid']])->update([
                    'update_time' => time(),
                    'type' => $param['customer']['type'],
                    'come_from' => $param['customer']['come_from'],
                    'intention' => $param['customer']['intention'],
                    'status' => $param['customer']['status'],
                ]);
            }else{
                Kehu::update_customers($data['cid'],['update_time' => time()]);
            }
            
            insert_user_log('处理了提醒');
            $this->success('处理成功',url('user/customer/remind'));
        }
        $config_customer = model('user_config')->where([ 'group'  => 'customer', 'status' => 1,'is_sys'=>1])->order('sort_order asc')->select();
        $customer = model('customer')->get($data['cid']);
        return $this->fetch(is_Client('set_remind'),[
            'config_customer' => $config_customer,
            'customer' => $customer,
        ]);
    }
    //跟踪记录删除
    public function del_remind()
    {
        if ($this->request->isPost()) {
            if ($this->delete_recovery('customer_remind', $this->request->param()) === true) {
                insert_user_log('删除了提醒记录');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }
    //导入客户数据
    public function upload_excel() {
        if ($this->request->isPost()) {
            $request = \think\Request::instance();
            $file = $request->file('excel');
            $save_path = ROOT_PATH . 'uploads/';
            $info = $file->move($save_path);
            //print_r($info);exit;

            $filename=$save_path . DIRECTORY_SEPARATOR . $info->getSaveName();
            if(file_exists($filename)) {//如果文件存在
                import('phpexcel.PHPExcel', EXTEND_PATH);
                if( strstr($filename,'.xlsx')){
                    $PHPReader = new \PHPExcel_Reader_Excel2007();
                }else{
                    $PHPReader = new \PHPExcel_Reader_Excel5();
                }
               //载入excel文件
               $PHPExcel = $PHPReader->load($filename);
               $sheet = $PHPExcel->getActiveSheet(0);//获得sheet
               $highestRow = $sheet->getHighestRow(); // 取得共有数据数
               $data=$sheet->toArray();

               for($i=0;$i<$highestRow;$i++){
                    $user['cname'] = trim($data[$i][0]);//excel中的第一栏
                    $user['mobile'] = $data[$i][1];//第二栏
                    $user['province'] = $data[$i][2];//第二栏
                    $user['city'] = $data[$i][3];//第二栏
                    $user['area'] = $data[$i][4];//第二栏
                    $user['type'] = $data[$i][5];//第二栏
                    $user['intention'] = $data[$i][6];//第二栏
                    $user['status'] = $data[$i][7];//第二栏
                    $user['come_from'] = $data[$i][8];//第二栏
                    $user['remark'] = $data[$i][9];//第二栏
                    $user['shop_id'] = session('user_auth.shop_id');
                    $user['uid'] = session('user_auth.user_id');
                    $user['create_time'] = time();
                    $user['is_public'] = '0';
                    //if(strlen($user['wxid'])==11 && substr($user['wxid'] , 0 , 1) =='1' ){//如果内容为11位的手机号,则入库
                    $cus = model('customer')->where(['mobile'=>$user['mobile']])->find();
                    if(!$cus and $i >= 1 and $user['cname']!='' and $user['mobile']!=''){
                        $new_datas[] = $user;
                    }
                }
                if(isset($new_datas) and count($new_datas)>0){
                    db('customer')->insertAll($new_datas, true);
                    $this->success('上传成功' . count($new_datas) . '条数据');
                }else{
                    $this->success('内容为空'.$new_datas);
                }
            // return $ret;
           }else{
               return array("resultcode" => -5, "resultmsg" => "文件不存在", "data" => null);
           }
        }
        return $this->fetch();
    }
  
    
}
